<template>
	<view class="menu-box">
		<!-- 图片轮播图以及推荐菜品显示 -->

		<view class="menu-swiper">
			<u-swiper :list="noticeList" keyName="image" showTitle :autoplay="swperAutoPlayFlag" :circular="true"
				radius="15px" height="22vh;"></u-swiper>
			<view class="menu-mask" v-show="frostedShow">
				<u-transition :show="swiperDish" mode="slide-right" :duration="1000" >
					<u-scroll-list @right="right" @left="left" :indicator="false">
						<view class="scroll-list transition" style="flex-direction: row;">
							<view class="scroll-list__goods-item" v-for="(item, index) in recommendDishList"
								:key="index" @click="AddDishFromRecommend(item)">
								<text class="scroll-list__goods-item__text">{{ item.dish_name.slice(0,6) }}</text>
								<image class="scroll-list__goods-item__image" :src="item.dish_img"></image>
								<text class="scroll-list__goods-item__text">￥{{ item.dish_price }}</text>
							</view>
						</view>
					</u-scroll-list>
				</u-transition>
			</view>

		</view>
		<!-- 菜单列表 -->
		<view class="menu-list-box">
			<view class="VerticalBox">

				<scroll-view class="VerticalNav nav" scroll-y scroll-with-animation :scroll-top="verticalNavTop"
					style="height:78vh;box-sizing: border-box;padding-bottom:10px;">
					<view class="cu-item" :class="index==tabCur?'text-orange cur':''" v-for="(item,index) in list"
						:key="index" @tap="TabSelect" :data-id="index">
						{{item.name}}
					</view>
				</scroll-view>


				<!-- 菜品数据 -->
				<scroll-view class="VerticalMain" scroll-y scroll-with-animation
					style="height:78vh;box-sizing:border-box;padding-bottom: 2px;" :scroll-into-view="'main-'+mainCur"
					@scroll="VerticalMain">
					<view class="padding-top padding-lr" v-for="(item,indexs) in list" :key="indexs"
						:id="'main-'+indexs">



						<view class="cu-bar solid-bottom bg-white">
							<view class="action">
								<!-- 菜品列表下的分类 -->
								<text class="cuIcon-title text-orange"></text>{{item.name}}
							</view>
						</view>
						<view class="cu-list menu-avatar">
							<view class="cu-item" v-for="(food,index) in dishWithType[indexs]" :key="index">
								<view class="cu-avatar lg" :style="{ 'background-image': 'url('+food.dish_img+')' }">
								</view>
								<view class="content">
									<view class="">{{food.name}}</view>
									<view class="text-gray text-sm flex dish-desc">
										<text>
											{{food.desc|filterDishDesc}}
										</text>
									</view>
									<view class="grid col-2 ">
										<view class="text-left">
											<text class="margin-right-xs">￥{{food.price}}</text>
											<text class="text-gray text-sm">销量:{{food.order_count}}</text>
										</view>

										<view class="text-right padding-right">
											<button @tap="addSub(indexs,2,index)" v-if="food.num > 0"
												class="cu-btn sm cuIcon lines-gray round padding-sm"
												style="font-size: 40upx;">
												<text class="cuIcon-move text-lg text-bold"></text>
											</button>
											<text v-if="food.num > 0"
												class="padding-lr-xs margin-lr-sl">{{food.num}}</text>
											<button @tap="startAdd(indexs,index)"
												class="cu-btn sm cuIcon bg-orange padding-sm" style="font-size: 40upx;">
												<text class="cuIcon-add text-lg text-bold"></text>
											</button>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 购物车 -->
			<view class="cu-modal bottom-modal" :class="modalName==true&&totalNum > 0?'show':''" @tap="hideModal">
				<view class="cu-dialog" @tap.stop="">
					<view class="padding-xs text-left bg-gray">
						<view class="shadow" @tap="clear"><text
								class="cuIcon cuIcon-delete padding-right-xs"></text>清空购物车
						</view>
					</view>
					<view style="min-height: 350upx;height: auto;">
						<view class="cu-list menu">

							<view class="cu-item" v-for="(food,index) in cartDish" :key="index" v-if="food.num>0">
								<view class="content text-left">
									<text>{{food.name}}</text>
								</view>
								<view class="action">
									<text class="padding-right">￥{{food.price*food.num}}</text>
									<button @click="cartDishAdd(food,false)"
										class="cu-btn sm cuIcon lines-gray round padding-sm" style="font-size: 40upx;">
										<text class="cuIcon-move text-lg text-bold"></text>
									</button>
									<text class="padding-lr-xs">x{{food.num}}</text>
									<button @click="cartDishAdd(food,true)"
										class="cu-btn sm cuIcon bg-orange padding-sm" style="font-size: 40upx;">
										<text class="cuIcon-add text-lg text-bold"></text>
									</button>
								</view>
							</view>

						</view>
					</view>
				</view>
			</view>
			<view class="cu-bar bg-white tabbar border shop foot" style="background-color: #f1f1f1;"
				v-if="totalNum > 0">
				<view class="action" @tap="openBag">
					<view class="cuIcon-goods">
						<view class="cu-tag badge">{{totalNum}}</view>
					</view>
					购物袋
				</view>
				<button class="action" style="width: 180px;">
					<view class="grid col-1 text-right padding-right-lg">
						<view class="text-bold text-lg margin-top-xs">￥{{totalPrice}}</view>
						<view class="text-grey  margin-top-xs">餐盒费￥0，配送费￥3</view>
					</view>
				</button>
				<view class="bg-gradual-blue cu-btn round " @tap="selectFlavor">{{flavorName}}</view>
				<view class="bg-orange submit" @tap="cat()">结算</view>
			</view>

		</view>


		<type-pick :flavorList="flavorList" @setFlavor="setFlavor" ref="flavor"></type-pick>

	</view>

</template>

<script>
	import {
		mapState,
		mapMutations,
		mapGetters
	} from 'vuex'
	// import Login from '@/components/Login.vue'
	import TypePick from '@/components/TypePick.vue'
	import {
		request
	} from '@/common/request.js'
	export default {
		components: {
			// Login
			TypePick
		},
		data() {
			return {

				// 推荐内容显示
				frostedShow: false,
				swiperDish: false,
				// 轮播图自动播放
				swperAutoPlayFlag: true,
				// 公告列表
				noticeList: [],
				recommendDishList: [{
					id: '0011',
					dish_name: '牛肉排',
					dish_price: '23￥',
					dish_img: '/static/foods/food1.jpg'
				}],
				// 菜单列表数据
				tabCur: 0,
				mainCur: 0,
				verticalNavTop: 0,
				load: true,
				swiperList: [],
				// 购物车显示
				modalName: false,
				// 菜品分类列表
				list: [],
				// 菜品列表
				// dishList: [],
				// 分类好的菜品列表
				// dishWithType: [],
				// 口味列表
				flavorList: [],
				flavor: 1,
				flavorName: '正常',
				// 已选菜品
				arr_sel: [],
				// // 口味名称列表
				// flavorNames: [],

			};
		},
		computed: {
			cartDish() {
				// const res = []
				const res = this.dishWithType.flat()
				return res
			},

			...mapGetters(['curCart']),
			...mapState(['dishWithType', 'totalNum', 'totalPrice', 'loginState', 'orderFlavor', 'dishList'])
		},
		filters: {
			// 菜品介绍超出隐藏
			filterDishDesc(desc) {
				if (desc.length > 28) {
					const text = desc.replace(/[\n-]/g, ' ');
					return text.slice(0, 29)
				}
				return desc
			}
		},

		watch: {
			totalNum(val) {
				if (val > 0) {
					this.maskShow()
					// 推荐列表的显示
					this.frostedShow = true
					this.swiperDish = true
					// 轮播图的播放
					this.swperAutoPlayFlag = false

				} else {
					// 轮播图的自动播放
					this.swiperDish = false
					setTimeout(() => {
						this.frostedShow = false
						this.swperAutoPlayFlag = true
					}, 1000)
				}
			},
			loginState(val) {
				if (val === false) {
					this.modalName = false
				}
			}

		},
		onLoad() {
			this.getDishType()
			this.getDishList()
			this.getNoticeList()
			this.getFlavorList()
			uni.showLoading({
				title: '加载中...',
				mask: true
			});

		},
		onReady() {
			uni.hideLoading()
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.getDishList()
		},
		methods: {
			...mapMutations(['ADD2CART', 'ADD2DISH', 'clearCart', 'ADDDISHLIST']),
			// 推荐菜品列表滑动
			left() {
				console.log('left');
			},
			right() {
				console.log('right');
			},
			// 遮罩层显示，同时也会发送请求，获取后台的推荐数据
			maskShow() {
				let cartDishId = []
				this.curCart.forEach(item => {
					cartDishId.push(item.id)
				})
				// cartDishId=[...new Set(cartDishId)]
				// console.log(cartDishId)
				request({
					url: '/smartOrder',
					method: 'POST',
					data: {
						cartId: cartDishId,
					}
				}).then(res => {
					console.log(res)
					this.recommendDishList = res.data

				}).catch(e => {
					console.log(e)
				})

			},
			// 点击推荐列表添加到菜品列表
			AddDishFromRecommend(item) {
				console.log(item)
				// if(!item) return 
				// const food = item
				item['name'] = item['dish_name']
				item['price'] = parseInt(item['dish_price'])
				this.ADD2CART({
					dish: item,
					add: true
				})
			},
			// 初始化添加菜品，确保之后的添加都是登录状态
			startAdd(indexs, index) {

				if (!this.loginState) {
					uni.showToast({
						icon: "error",
						title: "请先登录",
						duration: 2000
					})
					// 一秒后做路由跳转
					setTimeout(() => {
						uni.switchTab({
							url: '../me/me'
						})
					}, 1000)
					return
				}
				// 如果已经登录，则进行菜品添加
				this.addSub(indexs, 1, index)
			},
			// 菜单内容
			cat() {

				// 点击结算之后对菜品进行处理
				this.dishWithType.forEach((item, indexs) => {
					item.forEach((dish, index) => {
						if (dish.num > 0) {
							// console.log('当前是', dish.name, '数量大于0', indexs, index)
							this.arr_sel.push(dish)
						}
					})
				})
				uni.showModal({
					title: '确认支付',
					content: this.arr_sel.map(item => item.name + '-' + item.num + '-' + item.num * item.price +
							'\n')
						.join(''),
					success: res => {
						if (res.confirm) {
							console.log('点击了确认')
							const obj = {
								"total": this.totalPrice,
								"flavor_id": this.flavor,
								dishes: this.arr_sel
							}

							request({
								url: '/order',
								method: 'POST',
								data: obj
							}).then(res => {
								console.log(res)
								uni.showToast({
									title: '支付成功',
									duration: 2000
								})
								// 关闭弹窗
								this.modalName = false
								// 清空购物车
								this.clearCart()
								// 跳转路由
								setTimeout(() => [
									uni.switchTab({
										url: '../order/order'
									})
								], 2000)

							}).catch(e => {
								console.log(e)
								uni.showToast({
									title: '支付失败',
									icon: "error",
									duration: 2000
								})
							})

						} else if (res.cancel) {
							uni.showToast({
								title: '支付取消',
								icon: 'error',
								duration: 2000
							}, 2000)
						}
					}
				})
				// }

				setTimeout(() => {
					uni.hideToast()
				})
			},

			hideModal() {
				this.modalName = false;
			},
			// 购物车菜品的加减
			cartDishAdd(food, flag = true) {
				// console.log(food)
				if (flag) {
					// console.log('执行了购物车的加法操作')
					this.ADD2CART({
						dish: food,
						add: true
					})
				} else {
					// console.log('执行了购物车的减法操作')
					this.ADD2CART({
						dish: food,
						add: false
					})
				}
			},
			// 菜单栏页面的加减
			addSub(index, type, dishIndex) {
				// 根据索引获取当前food对象
				const food = this.dishWithType[index][dishIndex]
				// 加
				if (type == 1) {
					// console.log('执行了菜单栏内的加')
					this.ADD2CART({
						dish: food,
						add: true
					})
					// food["num"] = food["num"] + 1;
					// this.totalNum++;
					// this.totalPrice += food["price"];
				}
				// 减
				else {
					// console.log('执行了菜单栏内的减法操作')
					this.ADD2CART({
						dish: food,
						add: false
					})
				}
				if (this.totalNum == 0) {
					this.modalName = false;
				}

			},
			// 清空购物车或者提交订单后
			clear() {
				this.clearCart()
				this.flavor = 1
				this.modalName = false;
			},
			openBag() {
				// this.modalName = this.modalName == 1 ? 0 : 1;
				this.modalName = !this.modalName
			},
			TabSelect(e) {
				// console.log('当前的菜品分类点击')
				// console.log(e)
				this.tabCur = e.currentTarget.dataset.id;
				this.mainCur = e.currentTarget.dataset.id;
				this.verticalNavTop = (e.currentTarget.dataset.id - 1) * 50
			},
			VerticalMain(e) {

				// #ifdef MP-ALIPAY
				return false //支付宝小程序暂时不支持双向联动 
				// #endif
				let that = this;
				let tabHeight = 0;
				if (this.load) {
					for (let i = 0; i < this.list.length; i++) {
						let view = uni.createSelectorQuery().select("#main-" + this.list[i].id);
						view.fields({
							size: true
						}, data => {
							this.list[i].top = tabHeight;
							tabHeight = tabHeight + data?.height;
							this.list[i].bottom = tabHeight;
						}).exec();
					}
					this.load = false
				}
				let scrollTop = e.detail.scrollTop + 10;
				for (let i = 0; i < this.list.length; i++) {
					if (scrollTop > this.list[i].top && scrollTop < this.list[i].bottom) {
						this.verticalNavTop = (this.list[i].id - 1) * 50
						this.tabCur = this.list[i].id
						// console.log(scrollTop)
						return false
					}
				}
			},
			// 获取菜品分类
			getDishType() {
				request({
					url: '/type',
				}).then(res => {
					const typeList = res.typeList.map((item, index) => {
						item['id'] = index
						return item
					})
					// console.log('当前这是then之后的数据')
					// console.log(typeList)
					this.list = typeList
					// this.
				}).catch(e => {
					console.log(e)
				})
			},
			// 获取菜品列表
			getDishList() {
				request({
					url: '/dish',
				}).then(res => {
					// console.log(res)
					// this.ADDDISHLIST()
					const dishList = res.dishList.map(item => {
						item['num'] = 0
						item['price'] = parseInt(item.price)
						return item
					})
					const names = dishList.map(item => item.name)
					// console.log(names.length,names)
					const result = names.reduce((pre, cur) => {
						if (cur in pre) {
							pre[cur]++;
						} else {
							pre[cur] = 1;
						}
						return pre;

					}, {})
					console.log(result)
					// const names2 = [...new Set(names)]
					// console.log(names2.length,names2)


					this.ADDDISHLIST(dishList)
					// 构造新列表，根据type的索引将每一类菜品构造成新的数组
					for (let i = 0; i < this.list.length; i++) {
						const type_dish = dishList.filter(item => item.dish_type === this.list[i].name)
						this.ADD2DISH(type_dish)
					}
				}).catch(e => {
					console.log(e)
				})
			},
			// 获取口味列表
			getFlavorList() {
				request({
					url: '/flavor',
				}).then(res => {
					const result = res.flavorList.map(item => {
						// console.log(item)
						const obj = {
							id: item.id,
							name: item.name
						}
						return obj
					})
					this.flavorList.push(result)
					// console.log(this.flavorList)
					// this.flavorList = res.flavorList
					// this.flavorNames = res.flavorList.map(item=>item.name)
				}).catch(e => {
					console.log(e)
				})
			},
			// 设置flavor
			setFlavor(val) {
				// console.log('父组件接收到了子组件传递的flavor值',val,typeof(val))
				const data = this.flavorList[0][val]
				this.flavor = data.id
				this.flavorName = data.name
			},
			// 控制口味选择的弹窗
			selectFlavor() {
				// 对refs进行处理
				this.$refs.flavor.show = true
			},
			// 获取公告列表
			getNoticeList() {
				request({
					url: '/notice'
				}).then(res => {
					const data = res.noticeList
					this.noticeList = data
				})
			},


		},
	}
</script>
<style lang="scss" scoped>
	@import '@/static/css/main.css';

	// swiper中显示的文字做样式穿透
	/deep/ .u-swiper__wrapper__item__wrapper__title {
		font-size: 36rpx !important;
		line-height: 60rpx;
	}



	// 横向滚动列表指示器
	/deep/ .u-scroll-list__indicator__line {
		// margin-top: -8rpx !important;
	}


	.menu-box {

		//	轮播图
		.menu-swiper {
			position: relative;
			height: 21vh;
			padding: 2 6px;

			// 遮罩层
			.menu-mask {
				position: absolute;
				top: 0;
				left: 0;
				width: 100vw;
				height: 22vh;
				padding-top:20px;
				background: $uni-bg-color-mask;

				// rgba(255, 255, 255, 0.2);
				-webkit-backdrop-filter: blur(8px);
				backdrop-filter: blur(8px);
				border-radius: 10px;
				box-shadow: inset 0 0 6px rgba(255, 255, 255, 0.2);

				.menu-img-box {
					margin: 0 16px;
					border-radius: 4px;

					image {
						width: 60px;
						height: 60px;
					}
				}
			}

			.scroll-list {
				margin-top: 10px;
				@include flex(column);

				&__goods-item {
					margin: 0 20px;
					width: 60px;
					text-align: center;

					&__image {
						margin-top: 2px;
						display: block;
						width: 60px;
						height: 60px;
						border-radius: 4px;
					}

					&__text {
						color: #f56c6c;
						// text-align: center;
						font-size: 12px;
						white-space: nowrap;
						// text-align: center;
						margin-top: 2px;
					}
				}

				&__show-more {
					background-color: #fff0f0;
					border-radius: 3px;
					padding: 3px 6px;
					@include flex(column);
					align-items: center;

					&__text {
						font-size: 12px;
						width: 12px;
						color: #f56c6c;
						line-height: 16px;
					}
				}
			}
		}

		// 菜单列表
		.menu-list-box {
			height: 84vh;
			// padding-bottom: 100rpx;
			margin-top: 10px;
			width: 100vw;

			// background-color:$uni-color-primary;
			.fixed {
				position: fixed;
				z-index: 99;
			}

			.VerticalNav.nav {
				width: 200upx;
				height: 80vh;
				white-space: initial;
			}

			.VerticalNav.nav .cu-item {
				width: 100%;
				text-align: center;
				background-color: #f1f1f1;
				margin: 0;
				border: none;
				height: 50px;
				position: relative;
			}

			.VerticalNav.nav .cu-item.cur {
				background-color: #fff;
			}

			.VerticalNav.nav .cu-item.cur::after {
				content: "";
				width: 8upx;
				height: 30upx;
				border-radius: 10upx 0 0 10upx;
				position: absolute;
				background-color: #f37b1d;
				top: 0;
				right: 0upx;
				bottom: 0;
				margin: auto;
			}

			.VerticalBox {
				// height:1000rpx !important;
				display: flex;
			}

			.VerticalMain {
				background-color: #fff;
				flex: 1;
			}

			.cu-list.menu-avatar>.cu-item .content {
				width: calc(100% - 120upx);
			}

			.cu-list.menu-avatar>.cu-item {
				height: 100px;
			}


		}
	}
</style>
